package com.own.dondeestoy;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.acra.ACRA;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;
import org.w3c.dom.Document;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.own.dondeestoy.core.Card;

@ReportsCrashes(formKey = "", formUri = "https://arielcessario.cloudant.com/acra-dondeestoy/_design/acra-storage/_update/report", reportType = org.acra.sender.HttpSender.Type.JSON, httpMethod = org.acra.sender.HttpSender.Method.PUT, formUriBasicAuthLogin = "thothatakedieseralwasibl", formUriBasicAuthPassword = "R5SppqIVr84urPOeXrPve3tT",
// Your usual ACRA configuration
mode = ReportingInteractionMode.TOAST, resToastText = R.string.action_exit)
public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;
	// Privadas
	private static GoogleMap map;

	// Publicas
	public static Context context;
	public static LruCache<String, Bitmap> mMemoryCache;
	public static boolean showNotifications;
	public static CardAdapter cardAdapter;
	public static ListView lstCards;
	public static List<Card> cards;
	public static LatLng myPosition;
	public static LatLng auxPosition;
	public static ProgressBar mProgress;
	public static boolean isServiceStarted = false;
	public static int notCheckedTimes = 0;

	// Contantes Publicas
	public static final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
	public static final int cacheSize = maxMemory / 8;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// stopService(new Intent(getBaseContext(),
		// CheckLocationService.class));

		context = this;

		// Creo un location service
		CheckLocationService.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);

		mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
			@Override
			protected int sizeOf(String key, Bitmap bitmap) {
				// The cache size will be measured in kilobytes rather than
				// number of items.
				return bitmap.getByteCount() / 1024;
			}
		};

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}

		// Inicio el servicio
		if (!isServiceStarted) {
			startService();
		} else {
			stopService();
			startService();
		}

		// Dejo de mostrar notificaciones
		showNotifications = false;

		// Limpio todas las notificaciones si hace falta
		if (CheckLocationService.notificationManager != null)
			CheckLocationService.notificationManager.cancelAll();

		// Registro un receiver
		IntentFilter filter = new IntentFilter(
				"com.own.dondeestoy.isneartolocation");
		registerReceiver(myReceiver, filter);

		// Contador para saber cuantas veces se ejecutó el servicio, si se
		// ejecutó mas de 4 veces y nunca pasó por acá, hay que frenarlo.
		notCheckedTimes = 0;

	}

	// Recibe la notificado de que se terminaron de cargar todas las tarjetas y
	// actualiza la vista
	// Esto se hace porque el timer corre en thread distinto al del UI
	public BroadcastReceiver myReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			if (cards != null) {
				MainActivity.cardAdapter = new CardAdapter(
						MainActivity.context, R.layout.layout_card, cards);
				MainActivity.lstCards.setAdapter(MainActivity.cardAdapter);
				MainActivity.cardAdapter.notifyDataSetChanged();
				DummySectionFragment.setUpMapIfNeeded();
				notCheckedTimes = notCheckedTimes + 1;
				if (notCheckedTimes > 4) {
					stopService();
				}
			}

		}
	};

	public void navigate(View v) {

		Double lat = Double.valueOf(((TextView) ((View) v.getParent()
				.getParent()).findViewById(R.id.lblLat)).getText().toString());
		Double lng = Double.valueOf(((TextView) ((View) v.getParent()
				.getParent()).findViewById(R.id.lblLng)).getText().toString());

		LatLng location = new LatLng(lat, lng);
		auxPosition = location;
		GetRoute getRoute = new GetRoute();
		getRoute.execute("");

		mViewPager.setCurrentItem(1);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// startService(new Intent(getBaseContext(),
		// CheckLocationService.class));
		showNotifications = true;

	}

	@Override
	protected void onResume() {
		super.onResume();
		// stopService(new Intent(getBaseContext(),
		// CheckLocationService.class));
		if (CheckLocationService.notificationManager != null) {
			CheckLocationService.notificationManager.cancelAll();
		}
		stopService();
		startService();

		showNotifications = false;

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		stopService(new Intent(getBaseContext(), CheckLocationService.class));
		if (CheckLocationService.notificationManager != null)
			CheckLocationService.notificationManager.cancelAll();
		showNotifications = false;

	}

	@Override
	protected void onStop() {
		super.onStop();
		// startService(new Intent(getBaseContext(),
		// CheckLocationService.class));
		showNotifications = true;
	}

	// Method to start the service
	public void startService() {
		startService(new Intent(getBaseContext(), CheckLocationService.class));
		MainActivity.isServiceStarted = true;
	}

	// Method to stop the service
	public void stopService() {
		stopService(new Intent(getBaseContext(), CheckLocationService.class));

		MainActivity.isServiceStarted = false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			Intent intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			return true;
		case R.id.action_refresh:
			stopService();
			startService();
			break;
		case R.id.action_exit:
			Intent intentExit = new Intent(Intent.ACTION_MAIN);
			intentExit.addCategory(Intent.CATEGORY_HOME);
			intentExit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			stopService();
			startActivity(intentExit);
			break;
		}
		return false;
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	public void moreInfo(View v) {

		// #q=Carlos+Pellegrini+1181+Embajador&safe=off

		String name = ((TextView) ((View) v.getParent().getParent())
				.findViewById(R.id.lblName)).getText().toString()
				.replace(" ", "+");
		String address = ((TextView) ((View) v.getParent().getParent())
				.findViewById(R.id.lblAddress)).getText().toString()
				.replace(" ", "+");
		String descr = ((TextView) ((View) v.getParent().getParent())
				.findViewById(R.id.lblDescr)).getText().toString()
				.replace(" ", "+");

		StringBuilder sb = new StringBuilder();
		sb.append("https://www.google.com/#q=");
		sb.append(name);
		sb.append("+");
		sb.append(address);
		sb.append("+");
		sb.append(descr);
		sb.append("&safe=off");

		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(sb
				.toString()));
		startActivity(browserIntent);
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			if (position == 0) {
				Fragment fragment = new SuggestionsFragment();
				// Bundle args = new Bundle();
				// args.putInt(DummySectionFragment.ARG_SECTION_NUMBER,
				// position + 1);
				// fragment.setArguments(args);
				return fragment;
			}
			if (position == 1) {
				Fragment fragment = new DummySectionFragment();
				Bundle args = new Bundle();
				args.putInt(DummySectionFragment.ARG_SECTION_NUMBER,
						position + 1);
				fragment.setArguments(args);

				return fragment;
			}
			return null;
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			case 2:
				return getString(R.string.title_section3).toUpperCase(l);
			}
			return null;
		}
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class DummySectionFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";

		// private GoogleMap googleMap;
		// ArrayList<LatLng> mMarkerPoints;

		public DummySectionFragment() {
			// Getting Google Play availability status
			// int status =
			// GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.context);
			//
			// if(status!=ConnectionResult.SUCCESS){ // Google Play Services are
			// not available

			// int requestCode = 10;
			// Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
			// MainActivity.context, requestCode);
			// dialog.show();

			// }else { // Google Play Services are available

			// Initializing
			// mMarkerPoints = new ArrayList<LatLng>();
			// }
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main_dummy,
					container, false);

			Fragment fragment = (getFragmentManager()
					.findFragmentById(R.id.map));
			map = ((SupportMapFragment) fragment).getMap();

			setUpMapIfNeeded();
			// View rootView = inflater.inflate(R.layout.layout_map,
			// container, false);
			// TextView dummyTextView = (TextView) rootView
			// .findViewById(R.id.section_label);
			// dummyTextView.setText(Integer.toString(getArguments().getInt(
			// ARG_SECTION_NUMBER)));
			return rootView;
		}

		/**
		 * Configura el mapa de ser necesario
		 */
		public static void setUpMapIfNeeded() {
			if (map != null) {
				map.setMyLocationEnabled(true);
				// Centro el mapa en el congreso
				if (MainActivity.myPosition != null) {
					map.moveCamera(CameraUpdateFactory.newLatLngZoom(
							new LatLng(MainActivity.myPosition.latitude,
									MainActivity.myPosition.longitude), 14));
				}
				map.clear();
			}

			if (map != null && cards != null) {

				LatLng location = null;
				for (Card card : cards) {
					if (!card.getLat().equals("")) {

						location = new LatLng(Double.valueOf(card.getLat()),
								Double.valueOf(card.getLng()));
						map.addMarker(new MarkerOptions().position(location)
								.title(card.getName()));
					}
				}

			}
		}

		/**
		 * Set Marker point
		 * 
		 * @param position
		 * @param name
		 * @param info
		 */
		// private void setMarker(LatLng position, String name, String info) {
		// // Agregamos marcadores para indicar sitios de inter�ses.
		// /*
		// Marker myMaker = googleMap.addMarker(new MarkerOptions()
		// .position(position)
		// .title(name) //Agrega un titulo al marcador
		// .snippet(info) //Agrega informaci�n detalle relacionada con el
		// marcador
		// .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
		// //Color del marcador
		// */
		// }
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class SuggestionsFragment extends Fragment {

		Context currentContext = MainActivity.context;

		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		// public static final String ARG_SECTION_NUMBER = "section_number";

		public SuggestionsFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.layout_suggestions,
					container, false);

			// mProgress = (ProgressBar)
			// rootView.findViewById(R.id.progress_bar);
			// mProgress.setVisibility(View.INVISIBLE);
			MainActivity.lstCards = (ListView) rootView
					.findViewById(R.id.lstCards);

			return rootView;
		}

	}

	private class GetRoute extends AsyncTask<String, Void, String> {

		ArrayList<LatLng> directionPoint;
		PolylineOptions rectLine;

		@Override
		protected String doInBackground(String... params) {

			try {
				GMapV2Direction md = new GMapV2Direction();

				Document doc = md.getDocument(myPosition, auxPosition,
						GMapV2Direction.MODE_WALKING);
				directionPoint = md.getDirection(doc);
				rectLine = new PolylineOptions().width(10).color(
						Color.rgb(160, 195, 255));

				for (int i = 0; i < directionPoint.size(); i++) {
					rectLine.add(directionPoint.get(i));
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			return "Executed";
		}

		@Override
		protected void onPostExecute(String result) {
			map.clear();

			if (map != null && cards != null) {

				LatLng location = null;
				for (Card card : cards) {
					if (!card.getLat().equals("")) {

						location = new LatLng(Double.valueOf(card.getLat()),
								Double.valueOf(card.getLng()));
						map.addMarker(new MarkerOptions().position(location)
								.title(card.getName()));
					}
				}

			}

			map.addPolyline(rectLine);
			map.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 10));

			// Zoom in, animating the camera.
			map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}
}
